package com.cryann.mqttserver.mqttProcess.mqttMsgHandler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author cRyann
 * @date 2018/12/28 0028 15:28
 * @description:
 */
@Component
@Order(0)
public class MqttMsgCheckHandler implements CommandLineRunner {

    private static List<AbstractMqttHandler> mqttHandlerList = new ArrayList<>();

    @Autowired
    Map<String, AbstractMqttHandler> mqttHandlerMap;

    @Override
    public void run(String... args) {
        mqttHandlerList = new ArrayList(mqttHandlerMap.values());

        Stream.iterate(0, i -> i + 1).limit(mqttHandlerList.size() - 1).forEach(i -> {
            AbstractMqttHandler handler = mqttHandlerList.get(i);
            if ( i == 0 ) {
                handler.setPrevious(null);
                handler.setNext(mqttHandlerList.get(i + 1));
            } else if(i == mqttHandlerList.size()){
                handler.setPrevious(mqttHandlerList.get(i - 1));
                handler.setNext(null);
            }else {
                handler.setPrevious(mqttHandlerList.get(i - 1));
                handler.setNext(mqttHandlerList.get(i + 1));
            }
        });
    }

    public static AbstractMqttHandler mqttHandler() {
        if ( mqttHandlerList != null && mqttHandlerList.size() > 0 ) {
            return mqttHandlerList.get(0);
        }
        return null;
    }

    public static void delHandler(AbstractMqttHandler handler) {

    }

    /**
     *
     **/
    public static void addHandler(AbstractMqttHandler mqttHandler, boolean flag) {
        if ( flag ) {
            mqttHandlerList.get(0).setPrevious(mqttHandler);
            mqttHandler.setNext(mqttHandlerList.get(0));
        } else {
            mqttHandler.setPrevious(mqttHandlerList.get(mqttHandlerList.size()));
            mqttHandlerList.get(mqttHandlerList.size()).setNext(mqttHandler);
        }
    }

    public static List<AbstractMqttHandler> getMqttHandlers() {
        return mqttHandlerList;
    }

}
